package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.abc.robot01.R
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.vivemodel.CustomerDetailViewModel
import java.time.LocalDate
import java.time.format.DateTimeFormatter

/**
 *  客户管理详情
 */
class CustomerRenderDetails : BaseVoiceActivity() {
    private val viewModel: CustomerDetailViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.customerName.value = intent.getStringExtra("customerName")!!
        viewModel.customerPhone.value = intent.getStringExtra("customerPhone")!!
        viewModel.totalAmount.value = intent.getStringExtra("totalAmount")!!
        viewModel.load()

        setContent {
            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Row(modifier = Modifier.padding(30.px)) {
                        BackButton {
                        }
                        Spacer(modifier = Modifier.width(82.px))
                        Column {
                            BasicText(
                                text = "客户管理详情",
                                style = TextStyle(
                                    fontSize = 30.mysp,
                                    color = MYBLACK,
                                    fontWeight = FontWeight.Bold
                                ),
                            )
                            Spacer(modifier = Modifier.height(30.px))
                            Card(
                                colors = CardDefaults.cardColors()
                                    .copy(containerColor = Color.White),
                                modifier = Modifier
                                    .width(1400.px)
                                    .fillMaxHeight()
                                    .background(Color.Transparent),
                                shape = RoundedCornerShape(20.px)
                            ) {
                                Content()
                            }
                        }

                    }
                }
            }
        }
        Log.e(TAG, "onCreate");
    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    fun LazyItemScope.ItemRow(item: Item147) {
        Log.e(TAG, "ItemRow:" + item)
        if (item.isTitle) {
            Row {
                Spacer(modifier = Modifier.width(30.px))
                Text(
                    text = item.name,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        color = MYBLACK,
                        fontSize = 23.mysp,
                        fontWeight = FontWeight.Normal
                    ),
                    modifier = Modifier
                        .animateItemPlacement()
//                    .background(Color.Red)
                        .padding(vertical = 0.dp)
                )
            }
            return
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = Color.Transparent, // Background color for the item
                    shape = if (item.position == 0) RoundedCornerShape(
                        8.dp,
                        8.dp,
                        0.dp,
                        0.dp
                    ) else if (item.position == 1) RoundedCornerShape(
                        0.dp
                    ) else RoundedCornerShape(
                        0.dp,
                        0.dp,
                        8.dp,
                        8.dp
                    )
                )
                .padding(vertical = 8.dp, horizontal = 16.dp)
                .padding(bottom = 0.dp) // Space between items
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(), // Make Row fill the width of its container
                verticalAlignment = Alignment.CenterVertically
            ) {
                Spacer(modifier = Modifier.width(20.px))
                Image(
                    painter = painterResource(if (item.success) R.drawable.a2 else R.drawable.a4),
                    contentDescription = ""
                )
                Spacer(modifier = Modifier.width(30.px))
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.wrapContentSize()
                ) {
                    Image(painter = painterResource(R.drawable.a), contentDescription = "")
                    Text(
                        text = if (item.success) "渲染成功" else "渲染失败",
                        style = MaterialTheme.typography.bodyMedium.copy(
                            fontSize = 20.mysp,
                            fontWeight = FontWeight.Normal
                        ),
                        color = if (item.success) Color.Blue else Color.Red
                    )
                }
                Spacer(modifier = Modifier.width(30.px))
                Text(
                    text = item.device,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontSize = 23.mysp,
                        fontWeight = FontWeight.Normal
                    ),
                )
                Spacer(modifier = Modifier.width(30.px))
                Text(
                    text = item.name,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontSize = 23.mysp,
                        fontWeight = FontWeight.Normal
                    ),
                )
                Spacer(modifier = Modifier.weight(1f))
                Text(
                    text = item.date,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontSize = 23.mysp,
                        fontWeight = FontWeight.Normal
                    ),
                )
            }
        }
    }

    @Composable
    fun ColumnScope.Header() {
        val name by remember { viewModel.customerName }
        val totalAmount by remember { viewModel.totalAmount }
        val count by remember { viewModel.count }
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(start = 30.px)
        ) {
            BasicText(
                text = "用户名称: ${name}",
                style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
            )
            Spacer(modifier = Modifier.width(140.px))

            BasicText(
                text = "渲染总金额 :${totalAmount}",
                style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
            )
            Spacer(modifier = Modifier.width(140.px))
            BasicText(
                text = "渲染总次数:${count}",
                style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
            )
            Spacer(modifier = Modifier.weight(100.0f))
        }
    }

    @Composable
    fun Content() {
        Column {
            Spacer(modifier = Modifier.height(30.px))
            Header()
            Spacer(modifier = Modifier.height(30.px))
            DataList()
        }
    }

    @Composable
    fun DataList() {
        val items0 by viewModel.customerList.collectAsState()

        // 用于存储按月分组的结果
        val groupedData = mutableMapOf<String, MutableList<RetrofitService.Task>>()
        // 日期格式化器
        val formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss")
        for (item in items0) {
            if (item.endTime.isNotEmpty()) {
                // 解析日期并提取年和月
                val date = LocalDate.parse(item.endTime, formatter)
                val key = "${date.year}年${date.monthValue}月"
                // 将项目添加到相应的分组中
                groupedData.getOrPut(key) { mutableListOf() }.add(item)
            }
        }

        val dataList2 = mutableListOf<Item147>()

        // 打印分组结果
        for ((key, items) in groupedData) {
            Log.e(TAG, "分组: $key")
            dataList2.add(Item147(position = -1, isTitle = true, name = key))
            for (item in items) {
                dataList2.add(
                    Item147(
                        id=item.id,
                        position = 1,
                        isTitle = false,
                        success = item.status == 15,
                        name = item.designName,
                        date = item.endTime
                    )
                )
                Log.e(TAG, "  - ${item.designName} (ID: ${item.id})")
            }
        }


//        val dataList2 = items0.map {
//            Item147(position = 1, id = it.id,isTitle=false, success = it.status==15,name=it.designName,date=it.endTime)
//        }
//


        Log.e(TAG, "dataList:" + dataList2.size);
        LazyColumn {
            itemsIndexed(dataList2, key = { _, item -> item.id }) { index, item ->
                val isLastItem = index == dataList2.lastIndex
                ItemRow(item);
                if (isLastItem.not() && item.isTitle.not())
                    if (index < dataList2.lastIndex && dataList2[index + 1].isTitle.not()) {
                        HorizontalDivider(
                            modifier = Modifier.fillMaxWidth(),
                            thickness = 1.px,
                            color = MYBLACK_Percent10
                        )
                    }
            }
        }
    }

    companion object {
        val TAG = "客户管理详情"
    }

    data class Item147(
        /**
         *   0 为开始
         *   1 为中间
         *   2 为末尾.
         */
        val position: Int = -1,
        val id: String = "0",
        val isTitle: Boolean = false,
        val count: Int = 0,
        val success: Boolean = true,
        val device: String = "设备001",
        val name: String = "沿海地中海风格三室两厅",
        val date: String = "2023年7月23日 15:12"
    )
}
